'use strict';

const Controller = require('egg').Controller;

const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const fs = require('fs-extra');

const IS_MOCK = false;
const assets_host = 'http://localhost:8080';
const b_host = 'cn.buole.com';

// 代理服务端接口
proxy.on('proxyReq', function(proxyReq, req, res, options) {
  proxyReq.setHeader('host', b_host);
});

proxy.on('error', function(e) {
  console.error('代理错误', e);
});

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    await ctx.render('index.html', {
      page: ctx.params.page,
      assets_host: assets_host
    });
  }
  async proxy_assets() {
    // close koa default respond
    this.ctx.respond = false;

    const req = this.ctx.req;
    const res = this.ctx.res;

    proxy.web(req, res, {
      target: assets_host
    });
  }
  async proxy() {
    // 接口有时候比较慢，调样式的时候可以 mock 下，增加效率 
    const { ctx } = this;
    if (IS_MOCK) {
      var p = ctx.request.path.substr(1).replace(/\//g, '-');
      if (p) {
        const c = await fs.readFile(__dirname + `/../mock/${p}.json`, 'utf-8').catch(e => {
          return e;
        });
        if (!(c instanceof Error)) {
          return ctx.body = JSON.parse(c);
        }
      };
    };
    ctx.respond = false;

    const req = ctx.req;
    const res = ctx.res;

    proxy.web(req, res, {
      target: `http://${b_host}`
    });
  }
}

module.exports = HomeController;
